// 定义页面跳转函数
let iframe = null;
let navLast = null;
let fresh_link=new Date().getTime();
document.addEventListener('DOMContentLoaded', function() { 
    iframe = document.querySelector('iframe');
    const bottom = document.querySelector('.iot_bottom')
    iframe.height = window.screen.availHeight - bottom.scrollHeight;
    navLast = document.querySelector('.iot_home');
})
function jump(url){
    iframe.src = url+'?time='+fresh_link;
    //底部导航变色
    let navNew = document.querySelector('.iot_'+url.slice(2,-5));
    if( navLast !== navNew){
        imgLast = navLast.querySelector('img');
        spanLast = navLast.querySelector('span');
        imgNew = navNew.querySelector('img');
        spanNew = navNew.querySelector('span');
        imgLast.src =imgLast.src.slice(0,-12)+'default.png';
        imgNew.src = imgNew.src.slice(0,-11)+'selected.png';
        spanLast.className = '';
        spanNew.className = 'iot_selected_color';
        navLast = navNew;
    }
}
// 接收iframe中的信息
let hotiframe = null;
window.addEventListener('message', function(event) {  
    // 检查事件类型
    if ( event.data.type === 'details'){
        jumpDetails(event.data.id,event.data.number);
    }else if (event.data.type === 'hot'){
        hotiframe = document.querySelector('.iot_hotPage iframe')
        hotiframe.height = this.screen.availHeight - 3.72*window.screen.availWidth/10;;
        hotiframe.contentWindow.postMessage({url:event.data.URL,number:0}, '*');
        jumpHot(event.data.URL);
    }else if(event.data.type === 'order'){
        openOrder(event.data.Number);
    }
    // 处理接收到的消息  
    console.log('Received message:', event.data);  
    // 根据event.data中的内容进行相应的操作...  
});  
//热门页跳转函数
function jumpHot(url){
    const hotPage = document.querySelector('.iot_hotPage')
    const hotTop = hotPage.querySelector('.iot_hotTop')
    const hotBack = hotTop.querySelector('img')
    const hotDiv = hotTop.querySelector('div');
    const axiosData = sendingAxios(`https://pcapi-xiaotuxian-front.itheima.net${url}`);
    if (axiosData){
        axiosData.then(data=>{
            console.log(data)
            hotTop.style['background-image'] = 'url('+data.result.bannerPicture+')';
            for(let i = 0 ; i < data.result.subTypes.length;i++){
                const hotSpan= document.createElement('span');
                hotSpan.innerHTML = data.result.subTypes[i].title + '<div></div>';
                hotSpan.onclick=function(){
                    hotActive(i)
                    hotiframe.contentWindow.postMessage({url:url,number:i}, '*');
                }
                if(i === 0){
                    const hotSpandiv = hotSpan.querySelector('div')
                    hotSpandiv.className = 'iot_hotActive'
                }
                hotDiv.appendChild(hotSpan);
            }
            function hotActive(index){
                const hotSpandivs = hotDiv.querySelectorAll('div');
                for(let i = 0; i < hotSpandivs.length; i++){
                    hotSpandivs[i].className = '' 
                }
                hotSpandivs[index].className = 'iot_hotActive';
            }
        })
    }
    hotBack.onclick=function(){
        hotPage.style.position = 'fixed';
        hotPage.style.left = '100%';
        hotDiv.innerHTML = ''
    }
    hotPage.style.position = 'absolute';
    hotPage.style.left = '0';
}
//详情页跳转函数
let UnderDiv = [];
let I = 0;
let quantity = null;
document.addEventListener('DOMContentLoaded', function() {
    quantity = document.querySelector('.iot_UnderChoice .iot_quantity');
})
function jumpDetails(id,number){
    let details = document.querySelector('.iot_details');
    let afterDetails = null;
    if(number !== 0){
        if(number === 1){
            details.style.position = 'fixed'
        }else{
            details = document.querySelector('.iot_details'+(number-1))
            details.style.position = 'fixed'
        }
        details = document.querySelector('.iot_details'+number);
        //under详情
        const Under = details.querySelector('.iot_under');
        const underDiv = Under.querySelectorAll("div")
        underDiv[0].onclick=function(){underJump(id,number,0)}
        UnderDiv[number] = underDiv[0];
        UnderDiv[number].innerHTML = '<span>选择</span>请选择商品规格'
        underDiv[1].onclick=function(){underJump(id,number,1)}
        underDiv[2].onclick=function(){underJump(id,number,2)}
        afterDetails = details.cloneNode(true);
    }else{
        afterDetails = details.cloneNode(true);
        let cancel = details.querySelector('.iot_DetailsCancel');
        cancel.addEventListener('click', function(){
            backDetails(number,id);
        })
        //under详情
        const Under = details.querySelector('.iot_under');
        const underDiv = Under.querySelectorAll("div")
        underDiv[0].onclick=function(){underJump(id,number,0)}
        UnderDiv[number] = underDiv[0];
        UnderDiv[number].innerHTML = '<span>选择</span>请选择商品规格'
        underDiv[1].onclick=function(){underJump(id,number,1)}
        underDiv[2].onclick=function(){underJump(id,number,2)}
    }
    const axiosData = sendingAxios(`https://pcapi-xiaotuxian-front.itheima.net/goods?id=${id}`);
    if (axiosData){
        axiosData.then(data=>{
            console.log(data);
            const result = data.result;
            //banerr图片
            const bannerpicture = details.querySelectorAll('.iot_goodsBanner img')
            const spanNumber = details.querySelector('.iot_imgNumber')
            spanNumber.innerHTML = '1/5'
            const Difference = details.querySelector('.swiper-slide-active').getAttribute('aria-label').slice(0,1) - 1;
            for(let i = 0; i < 5 ;i++){
                bannerpicture[i].src = result.mainPictures[i];
                bannerpicture[i].addEventListener('touchend', function() {
                    const x = details.querySelector('.swiper-slide-active').getAttribute('aria-label').slice(0,1) - Difference;
                    const index = x > 0? x:x+5;
                    spanNumber.innerHTML = `${index}/5`;
                });
            }
            //价格
            const price = details.querySelector('.iot_price');
            price.innerHTML = result.price;
            //描述
            const above = details.querySelectorAll('.iot_choice .iot_above p')
            above[0].innerHTML = result.name;
            above[1].innerHTML = result.desc;
            const information = details.querySelector('.iot_information');
            for (let i = 0 ; i < result.details.properties.length; i++){
                let properties = document.createElement('div');
                properties.innerHTML = '<span></span><p></p>';
                const infoSpan = properties.querySelector('span');
                const infoP = properties.querySelector('p')
                infoSpan.innerHTML = result.details.properties[i].name;
                infoP.innerHTML = result.details.properties[i].value;
                information.appendChild(properties);
            }
            const picture = details.querySelector('.iot_picture');
            for(let i = 0; i < result.details.pictures.length; i++){
                const image = document.createElement('img')
                image.src = result.details.pictures[i];
                picture.appendChild(image);
            }
            const couple = details.querySelectorAll('.iot_couple');
            for(let i = 0 ; i < 2 ; i++){
                let img = couple[i].querySelectorAll('img')
                let a = couple[i].querySelectorAll('a')
                for(let j = 0 ; j < 2 ; j++){
                img[j].src = result.similarProducts[2*i+j].picture;
                img[j].id = result.similarProducts[2*i+j].id;
                a[j].addEventListener('click', function(event) { 
                    const id = this.querySelector('img').id;
                    event.preventDefault(); 
                    jumpDetails(id,number+1);
                }); 
            } 
            }
            for(let i = 0 ; i < 2 ; i++){
                let p = couple[i].querySelectorAll('p')
                    for(let j = 0 ; j < 4 ; j++){
                    if (j === 0){
                        p[j].innerHTML = result.similarProducts[2*i].name;
                    }else if(j === 1){
                        p[j].innerHTML = '￥'+result.similarProducts[2*i].price;
                    }else if(j === 2){
                        p[j].innerHTML = result.similarProducts[2*i+1].name;
                    }else if(j === 3){
                        p[j].innerHTML = '￥'+result.similarProducts[2*i+1].price;
                    }
                }
            } 
        })
        setTimeout(function(){
            details.style.position = 'absolute';
        },500)
        details.style.top = '0';
        details.style.left = '0';
        //底栏
        const  bottomChoice =details.querySelectorAll('.iot_bottomChoice div')
        const  bottomSpan =details.querySelectorAll('.iot_bottomChoice span')
        let cartIframe = null;
        if(number === 0){
            cartIframe  = document.querySelector('.iot_cartIframe')
        }else{
            cartIframe = document.querySelector('.iot_cartIframe'+number)
        }
         //新的cartIframe
        const  aftercartIframe = document.createElement('div')
        aftercartIframe.className = 'iot_cartIframe'+(number+1);
        aftercartIframe.innerHTML = '<img src="./icons/logo/back.png" alt=""><iframe src="./cart.html" frameborder="0"></iframe>';
        document.body.appendChild(aftercartIframe)
        bottomSpan[5].onclick=function(){
            console.log('md')
            //已有的cartIframe
            const cartIframeIn = cartIframe.querySelector('iframe')
            cartIframeIn.contentWindow.postMessage({type:'cartIframe',Number:number}, '*');
            details.style.position = 'fixed'
            setTimeout(function(){
                cartIframe.style.position = 'absolute';
            },500)
            cartIframe.style.height= window.screen.availHeight+'px'
            cartIframeIn.style.height= window.screen.availHeight+'px'
            cartIframe.style.left = '0';
            cartIframe.style['z-index'] = number+1
            const cartCancel = cartIframe.querySelector('img')
            cartCancel.onclick=function(){
                cartIframe.style.position = 'fixed';
                cartIframe.style.left = '100%';
                cartIframeIn.contentWindow.postMessage({type:'CancelcartIframe',Number:number}, '*');
                details.style.position = 'absolute'
            }
        }
        bottomChoice[0].onclick=function(){
            underJump(id,number,0)
            const addCart = document.querySelector('.iot_buy');
            addCart.style['background-color'] = '#ffa868';
            addCart.innerHTML = '加入购物车';
        };
        bottomChoice[1].onclick=function(){
            underJump(id,number,0)
            const buy = document.querySelector('.iot_buy');
            buy.style['background-color'] = '#27ba9b';
            buy.innerHTML = '立即购买';
        };
        // 提前创建新的页面
        afterDetails.className = 'iot_details'+(number+1);
        console.log(afterDetails)
        const swiperBanner = afterDetails.querySelector('.iot_goodsBanner')
        swiperBanner.id = `mySwiper${number+1}`
        afterDetails.style['z-index'] = number+1;
        cancel = afterDetails.querySelector('.iot_DetailsCancel');
        cancel.addEventListener('click', function(){
            backDetails(number+1);
        })
        document.body.appendChild(afterDetails);
        document.querySelector('script').innner = ``
        const swiper = new Swiper(`#mySwiper${number+1}`, {
            loop: true,
           });
        quantity.innerHTML = I = 0;
    }
}

//详情页返回函数
function backDetails(number){
    console.log(number)
    let details = document.querySelector('.iot_details');
    if(number !== 0){
        details = document.querySelector('.iot_details'+number);
        if(number === 1){
            beforeDetails = document.querySelector('.iot_details');
        }else{
            beforeDetails = document.querySelector('.iot_details'+(number-1));
        }
        beforeDetails.style.position = 'absolute'
        beforeDetails.style.top = '0'
    }
    details.style.position = 'fixed';
    details.style.left = '100%';
    const afterdetails = document.querySelector('.iot_details'+(number+1));
    const afteriframe = document.querySelector('.iot_cartIframe'+(number+1));
    setTimeout(function() {  
        try { 
            console.log(number)  
            document.body.removeChild(afterdetails);
            document.body.removeChild(afteriframe);
        } catch (error) {  
        } 
    },500)
    const bannerpicture = details.querySelectorAll(`.iot_goodsBanner img`)
    const price = details.querySelector('.iot_price');
    const above = details.querySelectorAll('.iot_choice .iot_above p')
    setTimeout(function() {  
        for(let i = 0; i < 5 ;i++){
            bannerpicture[i].src = ''
        } 
        price.innerHTML = '';
        above[0].innerHTML = '';
        above[1].innerHTML = '';
        const information = details.querySelector('.iot_information');
        information.innerHTML = '<p class="iot_infoUp">详情</p>'
        const picture = details.querySelector('.iot_picture');
        picture.innerHTML = '';
    }, 500);
    UnderDiv.pop()
    quantity.innerHTML = I = 0;
}
//under中的详情跳转
let unders = [];
let blackbg = [];
document.addEventListener('DOMContentLoaded', function() { 
    unders[0] = document.querySelector('.iot_UnderChoice');
    unders[1] = document.querySelector('.iot_Underaddress');
    unders[2] = document.querySelector('.iot_Underservice');
    blackbg = document.querySelector('.iot_blackbg');
})
let dataResult = null;
function underJump(id,number,index){
    if (index === 0){
        const axiosData = sendingAxios(`https://pcapi-xiaotuxian-front.itheima.net/goods?id=${id}`);
        if(axiosData){
            axiosData.then(data=>{
                dataResult = data.result;
                const options = unders[0].querySelector('.iot_underOption');
                let x = [];
                let y = [];
                for(let i = 0 ; i < dataResult.specs.length;i++){
                    console.log('h')
                    y[i] = dataResult.specs[i].values.length - 1;
                }
                for(let i = 0 ; i < dataResult.specs.length;i++){
                    const up = document.createElement('div')
                    up.className = 'iot_underUp'
                    up.innerHTML =  dataResult.specs[i].name;
                    const down = document.createElement('div')
                    down.className = 'iot_underDown'+i;
                    for (let j = 0 ; j < dataResult.specs[i].values.length; j++){
                        const childP = document.createElement('p');
                        childP.onclick= function(){
                            x[i] = j;
                            goodsJump(x,y,number);
                            activeP(i,j)
                        }
                        if (j === 0){
                            childP.className = 'iot_active';
                        }
                        childP.innerHTML = dataResult.specs[i].values[j].name
                        down.appendChild(childP);
                    }
                    options.appendChild(up);
                    options.appendChild(down);
                }
                function activeP(i,index){
                    childPs = options.querySelectorAll(`.iot_underDown${i} p`);
                    console.log(childPs)
                    options.querySelector(`.iot_underDown${i}`).querySelector('.iot_active').className = '';
                    childPs[index].className = 'iot_active'
                }
                for(let i = 0; i < dataResult.specs.length;i++){
                    x[i] = 0;
                }
                goodsJump(x,y,number);
            })
        }
        unders[0].style.transform = 'translate(0,-100%)';
        unders[0].style['z-index'] = number+1;
        const options = unders[0].querySelector('.iot_underOption');
        const underCancel = unders[0].querySelector('.iot_under-details img');
        function Cancel0(){
            console.log('kl')
            unders[0].style.transform = 'translate(0,0)';
            unders[0].style['z-index'] = 0;
            options.innerHTML = ''
            blackbg.style.hieght = 0;
            blackbg.style.display = 'none'
            blackbg.style['z-index'] = 0;
            blackbg.style.top = 0
        }
        blackbg.onclick=function(){Cancel0();}
        underCancel.onclick=function(){Cancel0();}
        unders[0].querySelector('.iot_underNumber .iot_plus').onclick=()=>{
            I++;
            if(I > 0){
                unders[0].querySelector('.iot_underNumber .iot_nimus').id = ''
            }
            quantity.innerHTML = I;
        }
        unders[0].querySelector('.iot_underNumber .iot_nimus').onclick=()=>{
            if(I > 1){
                I--;
            }else if(I == 1){
                unders[0].querySelector('.iot_underNumber .iot_nimus').id = 'iot_black'
                I--;
            }
            quantity.innerHTML = I;
        }
    }else if(index === 1){
        unders[1].style.transform = 'translate(0,-100%)';
        unders[1].style['z-index'] = number+1;
        const underCancel1 = unders[1].querySelector('img');
        function Cancel1(){
            unders[1].style.transform = 'translate(0,0)';
            unders[1].style['z-index'] = 0;
            blackbg.style.hieght = 0;
            blackbg.style.display = 'none'
            blackbg.style['z-index'] = 0;
            blackbg.style.top = 0
        }
        blackbg.onclick=function(){Cancel1();}
        underCancel1.onclick=function(){Cancel1();}
    }else if(index === 2){
        unders[2].style.transform = 'translate(0,-100%)';
        unders[2].style['z-index'] = number+1;
        const underCancel2 = unders[2].querySelector('img');
        function Cancel2(){
            unders[2].style.transform = 'translate(0,0)';
            unders[2].style['z-index'] = 0;
            blackbg.style.hieght = 0;
            blackbg.style.display = 'none'
            blackbg.style['z-index'] = 0;
            blackbg.style.top = 0
        }
        blackbg.onclick=function(){Cancel2();}
        underCancel2.onclick=function(){Cancel2();}
    }
    setTimeout(function(){
        blackbg.style.height = '100rem';
        blackbg.style.display = 'block'
        blackbg.style['z-index'] = number+1;
        blackbg.style.top = 0
    },500)
}
//点击函数
function goodsJump(x,y,number){
    const describe = unders[0].querySelector('.iot_under-details');
    let sum = 0;
    const p = describe.querySelectorAll('p');
    const img = unders[0].querySelector('img')
    for(let i = 0 ; i < x.length; i++){
        sum += x[i]+y[i]*i;
    }
    p[0].innerHTML = dataResult.skus[sum].price;
    p[1].innerHTML = '库存：'+dataResult.skus[sum].inventory;
    img.src = dataResult.skus[sum].picture;
    let sumString = ''
    for(let i = 0 ; i < x.length; i++){
        sumString += dataResult.specs[i].values[x[i]].name + '&nbsp;&nbsp;';
    }
    p[2].innerHTML = sumString;
    console.log(UnderDiv)
    UnderDiv[number].innerHTML = '<span>选择</span>'+sumString;
}

//订单详情
const screenWidth = this.screen.availWidth;
let order = null;
let underMark = null;
let orderUps = null;
document.addEventListener('DOMContentLoaded', function() {
    order = document.querySelector('.iot_order');
    underMark = order.querySelector('.iot_orderUp div')
    orderUps = document.querySelectorAll('.iot_orderUp span');
    for(let i = 0; i < orderUps.length; i++){
        orderUps[i].onclick=()=>{
            console.log('oo')
            underMark.style.left = (i+0.5)*screenWidth/5+'px'
            order.querySelector('.iot_orderContent').style.left = '-'+screenWidth*i+'px'
        }
    }
    order.querySelector('img').onclick=()=>{
        order.style.left = '100%'
        order.querySelector('.iot_orderContent').style.left = '0'
    }
})
function openOrder(number){
    order.style.left = '0'
    order.style.height = window.screen.availHeight +'px';
    underMark.style.left = (number+0.5)*screenWidth/5+'px'
    order.querySelector('.iot_orderContent').style.left = '-'+screenWidth*number+'px'
}

